<template>
  <!-- 生产批次规则表单弹窗 -->
  <div>
    <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="1000px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="160"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="规则类型" prop="ruleType">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.ruleType"
                  placeholder="请输入规则类型"
                  clearable
                />
                <span v-else>{{ formData.ruleType }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规则名称" prop="ruleName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.ruleName"
                  placeholder="请输入规则名称"
                  clearable
                />
                <span v-else>{{ formData.ruleName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="规则样例" prop="ruleSample">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.ruleSample"
                  placeholder="请输入规则样例"
                  clearable
                />
                <span v-else>{{ formData.ruleSample }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否启用" prop="isEnable">
                <el-switch
                  :disabled="props.isReadonly"
                  v-model="formData.isEnable"
                  inline-prompt
                  :active-value="1"
                  :inactive-value="0"
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div>
          <button
            class="custom-button"
            disabled
            style="background-color: #ccf783"
          >
            年标记
          </button>
        </div>
        <mesbatchnumberrule-descriptions
          :data="formData.year"
          :isReadonly="props.isReadonly"
          :start="2025"
        />
        <el-form-item
          label="是否需要奇偶年区分"
          prop="isEnable"
          style="margin-top: 10px"
        >
          <el-switch
            :disabled="props.isReadonly"
            v-model="formData.distinctDifferentiation"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
        <template v-if="formData.distinctDifferentiation === 1">
          <div>
            <button
              class="custom-button"
              disabled
              style="background-color: #54bcbd"
            >
              奇年月标记
            </button>
          </div>
          <mesbatchnumberrule-descriptions
            :data="formData.oddMonth"
            :isReadonly="props.isReadonly"
            suffix="月"
          />
          <div>
            <button
              class="custom-button"
              disabled
              style="background-color: #93d2f3"
            >
              偶年月标记
            </button>
          </div>
          <mesbatchnumberrule-descriptions
            :data="formData.evenMonth"
            :isReadonly="props.isReadonly"
            suffix="月"
          />
        </template>
        <template v-else>
          <div>
            <button
              class="custom-button"
              disabled
              style="background-color: #93d2f3"
            >
              月标记
            </button>
          </div>
          <mesbatchnumberrule-descriptions
            :data="formData.month"
            :isReadonly="props.isReadonly"
            suffix="月"
          />
        </template>
        <div>
          <button
            class="custom-button"
            disabled
            style="background-color: #de868f"
          >
            日标记
          </button>
        </div>
        <mesbatchnumberrule-descriptions
          :data="formData.day"
          :isReadonly="props.isReadonly"
          :column="12"
        />
        <div>
          <button
            class="custom-button"
            disabled
            style="background-color: #bfbf3d"
          >
            批次标记
          </button>
        </div>
        <mesbatchnumberrule-descriptions
          :data="formData.batch"
          :isReadonly="props.isReadonly"
          :column="12"
        />
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { ref } from "vue";
import { groupBy, range } from "lodash-es"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESBATCHNUMBERRULEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const resetDetailArray = (length) => {
  return range(0, length).map(() => null);
};

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  ruleType: "",
  ruleName: "",
  ruleSample: "",
  distinctDifferentiation: 1,
  isEnable: 1,
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  year: resetDetailArray(11),
  oddMonth: resetDetailArray(12),
  evenMonth: resetDetailArray(12),
  month: resetDetailArray(12),
  day: resetDetailArray(31),
  batch: resetDetailArray(31),
  details: [],
});

/** rules规则 */
const rules = reactive({
  ruleType: [
    { required: true, message: "请输入规则类型", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  ruleName: [
    { required: true, message: "请输入规则名称", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  ruleSample: [
    { required: true, message: "请输入规则样例", trigger: "blur" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.ruleType = "";
  formData.ruleName = "";
  formData.ruleSample = "";
  formData.distinctDifferentiation = 1;
  formData.isEnable = 1;
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.year = resetDetailArray(11);
  formData.oddMonth = resetDetailArray(12);
  formData.evenMonth = resetDetailArray(12);
  formData.month = resetDetailArray(12);
  formData.day = resetDetailArray(31);
  formData.batch = resetDetailArray(31);
  formData.details = [];
}

const loading = ref(false);

const buildDetails = (data, type, start = 1) => {
  return data.map((item, index) => ({
    ruleType: type,
    ruleName: start + index,
    ruleValue: item,
  }));
};

/** 生产批次规则保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      formData.details.length = 0;
      formData.details.push(...buildDetails(formData.year, 1, 2025));
      if (formData.distinctDifferentiation === 0) {
        formData.details.push(...buildDetails(formData.month, 2));
      } else {
        formData.details.push(...buildDetails(formData.oddMonth, 3));
        formData.details.push(...buildDetails(formData.evenMonth, 4));
      }
      formData.details.push(...buildDetails(formData.day, 5));
      formData.details.push(...buildDetails(formData.batch, 6));
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/mesbatchnumberrule/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

const parsingDetails = (data) => {
  return data.map(({ ruleValue }) => ruleValue);
};

async function getdetails() {
  const { data } = await request({
    url: "/mes/mesbatchnumberrule/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  if (data) {
    const group = groupBy(data, (item) => item.ruleType.toString());
    formData.year = parsingDetails(group["1"]);
    if (formData.distinctDifferentiation === 0) {
      formData.month = parsingDetails(group["2"]);
    } else {
      formData.oddMonth = parsingDetails(group["3"]);
      formData.evenMonth = parsingDetails(group["4"]);
    }
    formData.day = parsingDetails(group["5"]);
    formData.batch = parsingDetails(group["6"]);
  }
  formData.details = data;
  // formData.details = sondetails.data;
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
.cell-item {
  text-align: center;
}
.el-form--inline .el-form-item {
  margin-right: 0;
}
.custom-button {
  border: 1px solid #dcdfe6;
  color: black; /* 黑色文字 */
  padding: 5px 25px; /* 内边距 */
  text-align: center; /* 文字居中 */
  text-decoration: none; /* 去掉下划线 */
  display: inline-block; /* 行内块级元素 */
  font-size: 0.8rem; /* 字体大小 */
  margin: 4px 2px; /* 外边距 */
  border-radius: 4px; /* 圆角 */
}
</style>
